<?php
require_once 'bootstrap.php';
$opts = new Zend_Console_Getopt( array(
	'help|h' => 'help',
	'file-links|f=s' => 'File with links item',
	'test|t' => 'Save to txt files',
	'verbose|v' => 'Verbose mode' ) );
$logger = Zend_Log::factory( array(
	array(
		'writerName' => 'Stream',
		'writerParams' => array( 'stream' => 'advego.log' ),
		'formatterName' => 'Simple' ) ) );
Zend_Registry::set( 'logger', $logger );
try
{
	$opts->parse();
	if ( $opts->help )
	{
		die( $opts->getUsageMessage() );
	}
	if ( $opts->verbose )
	{
		$writer = new Zend_Log_Writer_Stream( 'php://output' );
		$logger->addWriter( $writer );
	}

	$test = false;
	if ( $opts->test )
	{
		$test = TRUE;
	}

	$logger->debug( 'Start script' );
	$message = sprintf( 'ARGV - %s ', print_r( $argv, true ) );
	$logger->debug( $message );

	$fileLinks = $opts->f;
	if ( empty( $fileLinks ) )
	{
		$fileLinks = Zend_Registry::get( 'config' )->get( 'found_links' );
	}
	if ( !file_exists( $fileLinks ) )
	{
		$message = sprintf( 'File not found', $fileLinks );
		throw new Exception( $message );
	}
	$linksItem = file( $fileLinks );
	$message = sprintf( 'Found %s links', count( $linksItem ) );
	$logger->debug( $message );
	$buyObj = new Advego_Buy( 'http://advego.ru', 'dansokolov@mail.ru', 'QWERTY' );
	$reportObj = new Advego_Report( time() );
	foreach ( $linksItem as $url )
	{
		$res = $buyObj->buy( $url, $test );

		switch ( $res )
		{
			case -1:
				$status = 'article is sold';
				break;
			case 1:
				$status = 'test buy';
				break;
			case 2:
				$status = 'article is buy';
				break;
			default:
				$status = 'none';
		}

		$message = sprintf( '%s - %s', $url, $status );
		$logger->debug( $message );

		$data = $buyObj->grab( $url );
		$filename = $reportObj->save( $data );

		$message = sprintf( 'Saved item - %s', $filename );
		$logger->debug( $message );
	}
	$logger->debug( 'Finish script' );
}
catch ( Zend_Console_Getopt_Exception $e )
{
	echo $e->getUsageMessage();
}
catch ( Exception $e )
{
	echo $e->getMessage();
}